package com.audaque.springboot.foshanupload.web.springsecuritycas.handler;

import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @author zgb
 * @desc 鉴权失败处理器
 * @date 2022-08-05 18:08:03
 */
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException exception) throws IOException, ServletException {
        exception.printStackTrace();
        log.error(exception.getMessage());
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();

        String username1 = null;

        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        if (authentication1 != null) {
            username1 = authentication1.getName();
        }


        //401——未授权
        httpServletResponse.setStatus(401);
        R r = new R<>();
        r.setSuccess(false);
        r.setCode(ResultCodeEnum.NOT_AUTHORIZATION.getCode());
        r.setMsg(username1 + "没有权限，访问失败!");

        try {
            out.write(objectMapper.writeValueAsString(r));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }
}
